package logic

import (
	"context"
	"encoding/json"
	"shuqi-novel/models/cache"
	"shuqi-novel/models/mysql"
	"time"

	"shuqi-novel/novelrpc/internal/svc"
	"shuqi-novel/novelrpc/novelrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserListLogic {
	return &UserListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserListLogic) UserList(in *novelrpc.UserListRequest) (*novelrpc.UserListResponse, error) {
	// todo: add your logic here and delete this line
	var users []mysql.User
	result, _ := cache.Rdb.Get(l.ctx, "userlist").Result()
	if result == "" {
		mysql.DB.Debug().Find(&users)
		marshal, _ := json.Marshal(users)
		cache.Rdb.Set(l.ctx, "userlist", marshal, time.Minute*3)
	} else {
		json.Unmarshal([]byte(result), &users)
	}

	var UserList []*novelrpc.UserList
	for _, user := range users {
		list := novelrpc.UserList{
			Title:  user.Title,
			Price:  float32(user.Price),
			Text:   user.Text,
			UserId: int64(user.ID),
		}
		UserList = append(UserList, &list)
	}
	return &novelrpc.UserListResponse{
		List: UserList,
	}, nil
}
